import React, {useState, useRef} from 'react';
import {View, Text, TouchableOpacity} from 'react-native';
import {Button} from '@rneui/base';
import Popover, {
  PopoverMode,
  PopoverPlacement,
} from 'react-native-popover-view';
import {round} from 'lodash';
import {getDefaultHeaderHeight} from '@react-navigation/elements';
import {
  useSafeAreaFrame,
  useSafeAreaInsets,
} from 'react-native-safe-area-context';
import {useMount} from 'ahooks';

export default () => {
  const [showPopover, setShowPopover] = useState(false);
  const sourceRef = useRef();

  const frame = useSafeAreaFrame();
  const insets = useSafeAreaInsets();
  const headerHeight = getDefaultHeaderHeight(frame, false, insets.top);

  const marginRight = 40;
  const modalContentWidth = 120;
  const pageContentWidth = (frame.width  - modalContentWidth) / 2;
  const x = -round((marginRight - pageContentWidth ) / pageContentWidth, 2);

  const marginTop = headerHeight;
  const modalContentHeight = 120;
  const pageContentHeight = (frame.height - frame.y - modalContentHeight) / 2;
  let y = round((marginTop - pageContentHeight ) / pageContentHeight, 2);

  useMount(() => {
    try {
      console.log('headerHeight', Platform.OS, headerHeight);
      console.log('frame', frame);
      console.log('insets', insets);
    } catch (e) {
      console.log('异常', e.message);
    }
  });

  return (
    <>
      <Popover
        isVisible={showPopover}
        backgroundStyle={{
          opacity: 0.8,
        }}
        popoverStyle={{
          // marginTop: marginTop,
          // marginRight: 10,
          width: modalContentWidth,
          height: modalContentHeight,
        }}
        // mode={PopoverMode.TOOLTIP}
        // placement={PopoverPlacement.TOP}
        // placement="top"
        popoverShift={{
          x: x,
          y: y,
        }}
        // offset={60}
        // verticalOffset={60}
        // arrowSize={{width: 16, height: 8}}
        // arrowShift={0.5}
        onRequestClose={() => setShowPopover(false)}>
        <View>
          <Text>内容y:{y}</Text>
          <Text>{PopoverPlacement.TOP}</Text>
        </View>
      </Popover>
      <Button
        title={`打开x:${x}`}
        onPress={() => {
          setShowPopover(true);
        }}
      />

      {/* <Popover
        placement={PopoverPlacement.BOTTOM}
        from={
          <TouchableOpacity>
            <Text>Press here to open popover!</Text>
          </TouchableOpacity>
        }>
        <Text>This is the contents of the popover</Text>
      </Popover> */}
    </>
  );
};
